package com.steve.summary.saga.common.repository;

import com.steve.summary.saga.common.model.Payment;
import com.steve.summary.saga.common.status.PaymentStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @Author: STEVE
 * @Description: 支付记录数据访问接口
 * @since: 2025-05-28
 */
public interface PaymentRepository extends JpaRepository<Payment, Long> {

    /**
     * 根据订单ID查询支付记录
     */
    Optional<Payment> findByOrderId(Long orderId);

    /**
     * 更新支付状态
     */
    @Modifying
    @Transactional
    @Query("UPDATE Payment p SET p.status = :status WHERE p.orderId = :orderId")
    int updatePaymentStatus(Long orderId, PaymentStatus status);

    /**
     * 检查订单是否已支付
     */
    @Query("SELECT CASE WHEN COUNT(p) > 0 THEN true ELSE false END FROM Payment p WHERE p.orderId = :orderId AND p.status = 'COMPLETED'")
    boolean isOrderPaid(Long orderId);

}
